package com.newlink.building.common_base.utils

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.StringRes
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import com.newlink.building.common_base.R
import com.newlink.building.common_base.base.BaseApplication
import java.lang.ref.WeakReference
import java.util.concurrent.ConcurrentHashMap

/**
 * 增强版Toast工具类
 * @Author: Enhanced by Claude
 * @Date: 2025-09-15
 * @Description: 内存安全、防重复、支持队列的Toast管理工具
 */
object ToastUtilsEnhanced {

    // Toast类型枚举
    enum class ToastType {
        SUCCESS, ERROR, WARNING, INFO, CUSTOM
    }

    // Toast配置数据类
    data class ToastConfig(
        val type: ToastType = ToastType.INFO,
        val duration: Int = Toast.LENGTH_SHORT,
        val gravity: Int = Gravity.BOTTOM,
        val xOffset: Int = 0,
        val yOffset: Int = 100,
        val customLayout: Int? = null,
        val showIcon: Boolean = true,
        val preventDuplicates: Boolean = true,
        val maxQueueSize: Int = 3
    )

    // 弱引用持有当前Toast，防止内存泄漏
    private var currentToastRef: WeakReference<Toast>? = null

    // Toast队列管理
    private val toastQueue = mutableListOf<ToastItem>()
    private var isShowingToast = false

    // 防重复显示的最后消息记录
    private val lastMessages = ConcurrentHashMap<String, Long>()
    private const val DUPLICATE_THRESHOLD = 2000L // 2秒内相同消息视为重复

    // 生命周期观察者
    private val lifecycleObservers = mutableMapOf<LifecycleOwner, LifecycleEventObserver>()

    // 主线程Handler
    private val mainHandler = Handler(Looper.getMainLooper())

    /**
     * Toast队列项
     */
    private data class ToastItem(
        val message: String,
        val config: ToastConfig,
        val timestamp: Long = System.currentTimeMillis()
    )

    // ========== 基础Toast方法 ==========

    /**
     * 显示短Toast
     */
    fun showShort(message: String, type: ToastType = ToastType.INFO) {
        show(message, ToastConfig(type = type, duration = Toast.LENGTH_SHORT))
    }

    /**
     * 显示长Toast
     */
    fun showLong(message: String, type: ToastType = ToastType.INFO) {
        show(message, ToastConfig(type = type, duration = Toast.LENGTH_LONG))
    }

    /**
     * 显示成功Toast
     */
    fun showSuccess(message: String) {
        show(message, ToastConfig(type = ToastType.SUCCESS))
    }

    /**
     * 显示错误Toast
     */
    fun showError(message: String) {
        show(message, ToastConfig(type = ToastType.ERROR, duration = Toast.LENGTH_LONG))
    }

    /**
     * 显示警告Toast
     */
    fun showWarning(message: String) {
        show(message, ToastConfig(type = ToastType.WARNING))
    }

    /**
     * 显示信息Toast
     */
    fun showInfo(message: String) {
        show(message, ToastConfig(type = ToastType.INFO))
    }

    // ========== 字符串资源支持 ==========

    fun showShort(@StringRes resId: Int, type: ToastType = ToastType.INFO) {
        val message = BaseApplication.context.getString(resId)
        showShort(message, type)
    }

    fun showLong(@StringRes resId: Int, type: ToastType = ToastType.INFO) {
        val message = BaseApplication.context.getString(resId)
        showLong(message, type)
    }

    fun showSuccess(@StringRes resId: Int) {
        val message = BaseApplication.context.getString(resId)
        showSuccess(message)
    }

    fun showError(@StringRes resId: Int) {
        val message = BaseApplication.context.getString(resId)
        showError(message)
    }

    fun showWarning(@StringRes resId: Int) {
        val message = BaseApplication.context.getString(resId)
        showWarning(message)
    }

    fun showInfo(@StringRes resId: Int) {
        val message = BaseApplication.context.getString(resId)
        showInfo(message)
    }

    // ========== 高级Toast方法 ==========

    /**
     * 自定义配置显示Toast
     */
    fun show(message: String, config: ToastConfig = ToastConfig()) {
        if (message.isBlank()) return

        // 防重复检查
        if (config.preventDuplicates && isDuplicateMessage(message)) {
            EnhancedLogger.d("ToastUtils", "跳过重复消息: $message")
            return
        }

        // 确保在主线程执行
        if (Looper.myLooper() == Looper.getMainLooper()) {
            enqueueToast(message, config)
        } else {
            mainHandler.post {
                enqueueToast(message, config)
            }
        }
    }

    /**
     * 立即显示Toast（清空队列）
     */
    fun showImmediately(message: String, config: ToastConfig = ToastConfig()) {
        if (message.isBlank()) return

        mainHandler.post {
            clearQueue()
            cancelCurrentToast()
            displayToast(message, config)
        }
    }

    /**
     * 显示居中Toast
     */
    fun showCenter(message: String, type: ToastType = ToastType.INFO) {
        val config = ToastConfig(
            type = type,
            gravity = Gravity.CENTER,
            yOffset = 0
        )
        show(message, config)
    }

    /**
     * 显示顶部Toast
     */
    fun showTop(message: String, type: ToastType = ToastType.INFO) {
        val config = ToastConfig(
            type = type,
            gravity = Gravity.TOP,
            yOffset = 100
        )
        show(message, config)
    }

    // ========== 队列管理 ==========

    /**
     * 将Toast加入队列
     */
    private fun enqueueToast(message: String, config: ToastConfig) {
        val toastItem = ToastItem(message, config)

        // 队列大小限制
        if (toastQueue.size >= config.maxQueueSize) {
            toastQueue.removeFirstOrNull()
        }

        toastQueue.add(toastItem)
        processQueue()
    }

    /**
     * 处理Toast队列
     */
    private fun processQueue() {
        if (isShowingToast || toastQueue.isEmpty()) return

        val toastItem = toastQueue.removeFirstOrNull() ?: return
        displayToast(toastItem.message, toastItem.config)
    }

    /**
     * 显示Toast
     */
    private fun displayToast(message: String, config: ToastConfig) {
        try {
            // 取消当前Toast
            cancelCurrentToast()

            val context = BaseApplication.context
            val toast = createToast(context, message, config)

            // 设置显示位置
            toast.setGravity(config.gravity, config.xOffset, config.yOffset)

            // 保存弱引用
            currentToastRef = WeakReference(toast)
            isShowingToast = true

            // 显示Toast
            toast.show()

            // 记录最后显示的消息
            recordMessage(message)

            // 设置显示完成回调
            val displayDuration = if (config.duration == Toast.LENGTH_LONG) 3500L else 2000L
            mainHandler.postDelayed({
                isShowingToast = false
                processQueue() // 继续处理队列
            }, displayDuration)

            // 记录日志
            EnhancedLogger.d("ToastUtils", "显示Toast: $message (类型: ${config.type})")

        } catch (e: Exception) {
            EnhancedLogger.e("ToastUtils", "显示Toast失败: $message", e)
            isShowingToast = false
            processQueue()
        }
    }

    /**
     * 创建Toast
     */
    private fun createToast(context: Context, message: String, config: ToastConfig): Toast {
        val toast = Toast(context)

        // 使用自定义布局或默认布局
        val layoutId = config.customLayout ?: when (config.type) {
            ToastType.SUCCESS -> R.layout.toast_success
            ToastType.ERROR -> R.layout.toast_error
            ToastType.WARNING -> R.layout.toast_warning
            ToastType.INFO -> R.layout.toast_info
            ToastType.CUSTOM -> R.layout.toast_custom
        }

        val view = try {
            LayoutInflater.from(context).inflate(layoutId, null)
        } catch (e: Exception) {
            // 如果自定义布局失败，使用默认布局
            EnhancedLogger.w("ToastUtils", "使用自定义布局失败，回退到默认布局", e)
            LayoutInflater.from(context).inflate(R.layout.toast_custom, null)
        }

        // 设置消息文本
        val textView = view.findViewById<TextView>(R.id.tv_prompt)
        textView?.text = message

        // 设置图标可见性
        val iconView = view.findViewById<View>(R.id.iv_icon)
        if (iconView != null && !config.showIcon) {
            iconView.visibility = View.GONE
        }

        toast.view = view
        toast.duration = config.duration

        return toast
    }

    // ========== 生命周期管理 ==========

    /**
     * 绑定生命周期（自动管理Toast）
     */
    fun bindLifecycle(lifecycleOwner: LifecycleOwner) {
        val observer = LifecycleEventObserver { _, event ->
            when (event) {
                Lifecycle.Event.ON_PAUSE -> {
                    // 暂停时隐藏Toast
                    cancelCurrentToast()
                }
                Lifecycle.Event.ON_DESTROY -> {
                    // 销毁时清理资源
                    unbindLifecycle(lifecycleOwner)
                }
                else -> { /* 其他事件不处理 */ }
            }
        }

        lifecycleOwner.lifecycle.addObserver(observer)
        lifecycleObservers[lifecycleOwner] = observer

        EnhancedLogger.d("ToastUtils", "绑定生命周期: ${lifecycleOwner.javaClass.simpleName}")
    }

    /**
     * 解绑生命周期
     */
    fun unbindLifecycle(lifecycleOwner: LifecycleOwner) {
        lifecycleObservers[lifecycleOwner]?.let { observer ->
            lifecycleOwner.lifecycle.removeObserver(observer)
            lifecycleObservers.remove(lifecycleOwner)
            EnhancedLogger.d("ToastUtils", "解绑生命周期: ${lifecycleOwner.javaClass.simpleName}")
        }
    }

    // ========== 工具方法 ==========

    /**
     * 检查是否为重复消息
     */
    private fun isDuplicateMessage(message: String): Boolean {
        val currentTime = System.currentTimeMillis()
        val lastTime = lastMessages[message]

        return lastTime != null && (currentTime - lastTime) < DUPLICATE_THRESHOLD
    }

    /**
     * 记录消息时间
     */
    private fun recordMessage(message: String) {
        lastMessages[message] = System.currentTimeMillis()

        // 清理过期记录
        val currentTime = System.currentTimeMillis()
        lastMessages.entries.removeAll { (_, time) ->
            currentTime - time > DUPLICATE_THRESHOLD * 2
        }
    }

    /**
     * 取消当前Toast
     */
    fun cancelCurrentToast() {
        currentToastRef?.get()?.cancel()
        currentToastRef = null
    }

    /**
     * 清空Toast队列
     */
    fun clearQueue() {
        toastQueue.clear()
        EnhancedLogger.d("ToastUtils", "清空Toast队列")
    }

    /**
     * 获取队列大小
     */
    fun getQueueSize(): Int = toastQueue.size

    /**
     * 清理所有资源
     */
    fun cleanup() {
        cancelCurrentToast()
        clearQueue()
        lastMessages.clear()
        lifecycleObservers.clear()
        isShowingToast = false
        EnhancedLogger.d("ToastUtils", "清理Toast资源")
    }

    // ========== 扩展方法 ==========

    /**
     * 安全显示Toast（处理异常）
     */
    fun safeShow(message: String?, type: ToastType = ToastType.INFO) {
        if (!message.isNullOrBlank()) {
            try {
                show(message, ToastConfig(type = type))
            } catch (e: Exception) {
                EnhancedLogger.e("ToastUtils", "安全显示Toast失败: $message", e)
            }
        }
    }

    /**
     * 条件显示Toast
     */
    fun showIf(condition: Boolean, message: String, type: ToastType = ToastType.INFO) {
        if (condition) {
            show(message, ToastConfig(type = type))
        }
    }

    /**
     * 显示调试Toast（仅在调试模式下）
     */
    fun showDebug(message: String) {
        if (DeviceUtilsEnhanced.isDebugMode(BaseApplication.context)) {
            show("[DEBUG] $message", ToastConfig(type = ToastType.INFO, duration = Toast.LENGTH_SHORT))
        }
    }
}